//
//  KSFormHItem+Extension.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/22.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
import Kingfisher

extension KSFormBaseItem {
  
    // 是否必填    判空使用
    func isMustInput() -> Bool {
        return self.appearance.mustInput
    }
  
     
    func getNowType() -> KType {
        return type
    }
   
    
     // MARK: - 设置 值 set datasource
    // 设置textview的背景
    func setTextViewBgColor(color:UIColor) {
        self.textView.backgroundColor = color

    }
    // 设置 加减控件的最大 值
    func setCountViewMax(_ value:Double) {
        self.countV.maxValue = value
    }
    // 设置 加减控件的 最小值
    func setCountViewMin(_ value:Double) {
        self.countV.minValue = value
    }
    // 设置 加减幅度
    func setFuduNumber(_ value:Double) {
        self.countV.fuduNumber = value
    }
    
    
    func setCountVCurrentValue(_ value:Double) {
        self.countV.currentNumber = value
    }
    // 处理标题
    func configTitle(_ str:String?,color:UIColor? = nil) {
        var showStr = str.unwrap
        if showStr.contains("*") {
            self.appearance.mustInput = true
            self.asterisLab.isHidden = false
            showStr = showStr.replacingOccurrences(of: "*", with: "")
        } else {
            self.appearance.mustInput = false
            self.asterisLab.isHidden = true
         }
        
        self.tpTitleLab.text = showStr
//        if showStr.count > 8 {
//            self.tpTitleLab.font = UIFont.systemFont(ofSize: 14)
//        } else {
            self.tpTitleLab.font = UIFont.systemFont(ofSize: 17)
//        }
        configPlaceholder()
   
           
        titleLabColorAdapt()
        if color.isSome {
            self.appearance.tpTitleColor = color!
        }
    }
    func configPlaceholder() {
        var showPlaceHolder = ""
        if self.appearance.placeholder.isNone {
            var preStr = "请输入"
            if self.actionClosure.isSome {
                preStr = "请选择"
            }
            showPlaceHolder = "\(preStr)\(self.tpTitleLab.text.unwrap)"
        } else {
            showPlaceHolder = self.appearance.placeholder.unwrap
        }

           if disabled {
               self.textView.placeHolder = ""
           } else {
   
               self.textView.placeHolder = showPlaceHolder
           }
    }
    
    
    // 设置必填
     func setMustInput(_ bool:Bool) {
         self.appearance.mustInput = bool
         self.asterisLab.isHidden = !self.appearance.mustInput
        }
    // 设置标题
    func setTempTitle(_ str:String?,color:UIColor? = nil) {
         self.configTitle(str,color: color)
        }
    // 设置内容
    func setVal(_ str:String?) {
        previousTextViewStr = str.unwrap
        self.textView.text = str
        if appearance.limitTextCount > 0 {
            NotificationCenter.default.post(name: UITextView.textDidChangeNotification, object: nil)
        }
        
        // 兼容两行的情况不能完全显示
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            let calStr = NSMutableAttributedString(string: str.unwrap, attributes: [.font: self.textView.font ?? .systemFont(ofSize: UIFont.systemFontSize)])
            if calStr.boundingRect(with: self.textView.ks_size, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).height > ((self.textView.font?.pointSize ?? UIFont.systemFontSize) + 4) {
                self.textView.contentOffset = .init( x: 0, y: self.textView.textContainerInset.top)
            }
        }
        
//        DispatchQueue.main.async {
//            let calStr = NSMutableAttributedString(string: str.unwrap, attributes: [.font: self.textView.font ?? .systemFont(ofSize: UIFont.systemFontSize)])
//            if calStr.boundingRect(with: self.textView.ks_size, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).height > ((self.textView.font?.pointSize ?? UIFont.systemFontSize) + 4) {
//                self.textView.contentOffset = .init( x: 0, y: self.textView.textContainerInset.top)
//            }
//        }
     }
    // 设置内容
    func setImage(_ url:String?) {
        if  let imageUrl = URL(string:url.unwrap) {
            let resource = KF.ImageResource(downloadURL: imageUrl)
            self.imageV.kf.setImage(with: resource, placeholder: nil)
        }
    }
    func setImage(_ img:UIImage) {
             self.imageV.image = img
    }
    // 设置内容
    func setattriVal(_ attr:NSAttributedString) {
         self.textView.attributedText = attr
     }
    // 设置placeholder
    func setPlaceholder(_ str:String?) {
         self.textView.placeHolder = str
     }
    // 设置提示内容
    func setTipStr(_ str:String,color:String? = nil,tipAligment:NSTextAlignment? = nil) {
        self.appearance.tipStr = str
        tipLab.text = self.appearance.tipStr
        if color.isSome {
            self.appearance.tipColor = color!
            tipLab.textColor = UIColor(kshex: self.appearance.tipColor!)
        }
        if tipAligment.isSome {
            self.appearance.tipAligment = tipAligment!
            tipLab.textAlignment = tipAligment!
        }
    }
  
    // 设置segment
     func setSegmentIndex(_ index:Int) {
         self.segment.selectedSegmentIndex = index
     }
    func setSegmentSelectTitle(_ str:String) {
        let indd = self.appearance.segTitleArr?.getIndexFor({ strrr in
          return strrr == str
        })
        if indd.isSome {
            self.segment.selectedSegmentIndex = indd!
        } else {
            self.segment.selectedSegmentIndex = -1
        }
        
    }
 
    
    //设置选中
    func setSelect(_ str:String) {
        for y in 0..<self.selectBtnArr.count {
            if self.selectBtnArr[y].titleLabel?.text == str {
                self.selectBtnArr[y].isSelected = true
            } else {
                self.selectBtnArr[y].isSelected = false
            }
         }
     }
     
     
    

   
    @objc func textfieldChange(sender:UITextField) {
        if let clo = textValueChangeClo {
            clo(sender.text.unwrap)
        }
    }
    @objc func textfieldEndEdit(sender:UITextField) {
        if let clo = textEndEditClo {
            clo(sender.text.unwrap)
        }
    }
    // 设置 电话号码输入模式  非负数  无小数点
     func setPhoneInput() {
     
         textView.keyboardType = .phonePad
         textView.textContentType = .telephoneNumber
        
        
    }
  
    // 设置 整数输入
     func setIntegerInput() {
      
         textView.autocorrectionType = .no
         textView.keyboardType = .phonePad
     }
    // 设置 密码输入
    func setSecureEntry(_ flag:Bool) {
        textView.isSecureTextEntry = flag
      }
 
//    func setAssistBtnImg(_ imgstr:String?) {
//        self.appearance.assistImgStr = imgstr
//        assistBtn.setBackgroundImage(UIImage(named:self.appearance.assistImgStr.unwrap), for: .normal)
//        }
   
    // 设置小数点键盘
     func setDemiKeyborad() {
         
       
         textView.autocorrectionType = .no
         textView.keyboardType = .decimalPad
     }
  
    // MARK: - 添加控件
    // 添加跟随的 单位 （在右侧）
     func  addDesc() {
        self.addSubview(descLab)
        descLab.snp.makeConstraints { make in
            make.right.equalTo(self).offset(-2)
            make.top.equalTo(self).offset(1)
            make.bottom.equalTo(self).offset(-1)
        }
    }
   
    
    // 添加 纯提示文字
     func addTipLab() {
         self.assistBtn.isHidden = true
        self.addSubview(tipLab)
        tipLab.text = self.appearance.tipStr
        if self.appearance.tipFont.isSome {
            tipLab.font = self.appearance.tipFont!
        }
         if self.appearance.tipColor.unwrap != "" {
             tipLab.textColor = UIColor(kshex: self.appearance.tipColor!)
         }
        if self.appearance.tipAligment.isSome {
            tipLab.textAlignment = self.appearance.tipAligment!
        }
        tipLab.snp.makeConstraints { make in
            make.left.equalTo(self).offset(12)
             make.right.equalTo(self).offset(-12)
            make.top.equalTo(self).offset(10)
          }
    }
     func addCountView() {
         
         assistBtn.extHidden(hidden: true)
        
        let couWidth:CGFloat = 150
        let couHeight:CGFloat = ItemHHeight - 6
        // 给内部控件一个布局框架
        countV.frame = CGRect(x: 0, y: 3, width: couWidth, height: couHeight)
        self.addSubview(countV)
        countV.snp.makeConstraints { make in
            make.right.equalTo(self).offset(-self.appearance.contentTrailing)
            make.width.equalTo(couWidth)
            make.height.equalTo(couHeight)
            make.centerY.equalTo(self)
        }
     
        countV.valueBlock = { number in
            if let clo = self.countViewChangeClo {
                clo(number)
            }
        }
     
    }
  
     func  addImage() {
         self.addSubview(imageV)
        imageV.snp.makeConstraints { make in
            make.right.equalTo(self).offset(-self.appearance.contentTrailing + 3)
            make.centerY.equalTo(self)
            make.width.height.equalTo(ItemHHeight - 6)
         }
    }
  
//     func  addArrow() {
//        if arrowMark.superview.isNone {
//            self.addSubview(arrowMark)
//            self.layoutArrow()
//        }
//    }
//  
//    
//    
//     func removeArrow() {
//        if arrowMark.superview.isSome {
//            arrowMark.removeFromSuperview()
//        }
//    }
     func  bgAddTap() {
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [unowned self] _ in
            if self.disabled == false {
                if let clo = self.actionClosure {
                    clo()
                }
            }
            
         }
         self.addGestureRecognizer(tap)
    }
   
    
     func addSigleSeArr() {
        self.lastBtn = nil
        self.selectBtnArr.removeAll()
        let needColored = self.appearance.selectColorArr.isSome
        for i in 0..<self.appearance.selectConArr!.count {
            let btn = FormItButton()
            if needColored {
                btn.setTitleColor(self.appearance.selectColorArr![i], for: .normal)
            }
            btn.addTouchUpInSideAction { [i] currentBtn in
                for y in 0..<self.selectBtnArr.count {
                    self.selectBtnArr[y].isSelected = false
                }
                currentBtn.isSelected = true
                if let clo = self.singleSeclectChangeClo {
                    clo(i)
                }
            }
            selectBtnArr.append(btn)
             btn.setTitle(self.appearance.selectConArr![i], for: .normal)
            self.addSubview(btn)
            btn.snp.makeConstraints { make in
                make.right.equalTo(self).offset(-self.appearance.contentTrailing)
                make.height.equalTo(30)
                make.left.equalTo(self.tpTitleLab.snp.right).offset(5)
                if self.lastBtn.isNone {
                    make.top.equalTo(self).offset(3)
                } else {
                    make.top.equalTo(self.lastBtn!.snp.bottom)
                }
            }
            self.lastBtn = btn
        }
    }
     func addSegment() {
         self.assistBtn.isHidden = true
        let widthS:CGFloat = CGFloat(self.appearance.segTitleArr!.count) * self.appearance.segWidth
        self.addSubview(segment)
        segment.snp.makeConstraints { make in
            make.width.equalTo(widthS)
            make.height.equalTo(30)
            make.right.equalTo(self).offset(-(self.appearance.arrowTrailing + 5))
            make.centerY.equalTo(self)
        }
        if let segBg = self.appearance.segBg {
            segment.backgroundColor = segBg
 
            let textAttrs: [NSAttributedString.Key : Any] = [
                .foregroundColor: segBg
            ]
            segment.setTitleTextAttributes(textAttrs, for: .selected)
            let textAttrs2: [NSAttributedString.Key : Any] = [
                .foregroundColor: UIColor.white
            ]
            segment.setTitleTextAttributes(textAttrs2, for: .normal)
            
         }
 
        for i in 0..<self.appearance.segTitleArr!.count {
            segment.insertSegment(withTitle: self.appearance.segTitleArr![i], at: i, animated: true)
            
        }
        segment.selectedSegmentIndex = 0
        segment.addSegmentChangeClosure { segmentx in
            if let clo = self.segmentChangeClo {
                let tit = self.appearance.segTitleArr![segmentx.selectedSegmentIndex]
                 clo(segmentx.selectedSegmentIndex,tit)
            }
        }
     }
 
}
extension KSFormBaseItem:UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {


        if self.appearance.integerInput {
            guard textView.text.validateInteger() else {
                textView.text = previousTextViewStr
                return
            }
            
        }
        if self.appearance.twoDemiInput || self.appearance.negativeTwoDemiInput {
            guard textView.text.validateTwoDecimal() else {
                textView.text = previousTextViewStr
                return
            }
          
        }
        if self.appearance.threeDemiInput {
            guard textView.text.validateThreeDecimal() else {
                textView.text = previousTextViewStr
                return
            }
     
        }
        if self.appearance.fourDemiInput {
            guard textView.text.validateFourDecimal() else {
                textView.text = previousTextViewStr
                return
            }
     
        }
        if self.appearance.regularExp != "" {
            
            guard textView.text.valiRagular(self.appearance.regularExp) else {
                textView.text = previousTextViewStr
                return
            }
            
        }
            
         
        
        previousTextViewStr = textView.text
      
        if let clo = textValueChangeClo {
            clo(textView.text.unwrap)
        }
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if let clo = textEndEditClo {
            clo(textView.text.unwrap)
        }
    }
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        if self.disabled {
            return false
        }
 // actionClosure 实现是  按钮事件，不弹出键盘
        if let clo = self.actionClosure, !self.appearance.isEditAndActionBoth {
            if self.disabled == false {
                clo()
            }

            return false
        } else {
            return true
        }
    }
}


extension KSFormBaseItem:UITextFieldDelegate {
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if let clo = self.actionClosure {
            if self.disabled == false {
                clo()
            }
            return false
        } else {
            return true
        }
        
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.textView.resignFirstResponder()
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if self.appearance.integerInput {
            if let oldString = textField.text {
                let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!, with: string)
                return newString.validateInteger()
            }
        }
        if self.appearance.twoDemiInput || self.appearance.negativeTwoDemiInput {
            if let oldString = textField.text {
                let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!, with: string)
                return newString.validateTwoDecimal()
            }
        }
        if self.appearance.threeDemiInput {
            if let oldString = textField.text {
                let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!, with: string)
                return newString.validateThreeDecimal()
            }
        }
        if self.appearance.regularExp != "" {
            if let oldString = textField.text {
                let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!, with: string)
                return newString.valiRagular(self.appearance.regularExp)
            }
        }
            return true
       }
}

